// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-11-12

#ifndef __SVR_USERMSG_H_COMMON_SVR_BASE__
#define __SVR_USERMSG_H_COMMON_SVR_BASE__

#pragma once

#include <common/base/thread.h>
#include <common/base/mempool.h>
#include <common/svr_base/base_list.h>
#include <common/svr_base/PfmcStat.h>

namespace JoyServer
{

class CJoyThreadingMsgQueue;

class CJoyThreadingMsg : public CJoyPoolObject
{
public:
    CJoyThreadingMsg*    m_next;
    CJoyThreadingMsg*    m_prev;
protected:
    CJoyThreadingMsgQueue*  m_queue;
protected:
    friend class CJoyThreadingMsgQueue;

    virtual void OnExecute() = 0;
public:
    CJoyThreadingMsg();
    virtual ~CJoyThreadingMsg();
};

class CJoyThreadingMsgQueue
{
protected:
    typedef CJoyDualList<CJoyThreadingMsg>   CMsgList;

    CJoyCriticalSection m_lock;
    CMsgList    m_msgs;
    HANDLE  m_event;
    HANDLE  m_thread;
    volatile bool    m_stop;

    static DWORD WINAPI sProcessMsgProc(void*);
    virtual void ProcessMsgProc();
public:
    CJoyThreadingMsgQueue();
    virtual ~CJoyThreadingMsgQueue();

    CJoyThreadingMsg* PeekMsg();
    CJoyThreadingMsg* WaitMsg();
    void QueueMsg(CJoyThreadingMsg* msg);

    virtual bool Create();
    virtual void Destroy();

    HANDLE GetThreadHandle()
    {
        return m_thread;
    }
};

} // namespace JoyServer

#endif  // __SVR_USERMSG_H_COMMON_SVR_BASE__